<template>
  <div class="update-img"
       v-loading="loading"
       :element-loading-text="'上传中...'+progress"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <div style="color:#333;">{{videoNema}}</div>
    <div style="float:left"
         class="img-box"
         v-if="dataList">
      <video @canplaythrough="myFunction"
             :src="dataList?dataList:''"
             controls
             accept="video/*"
             height="120"
             width="120">您的浏览器不支持 video 标签。</video>
      <i class="clear-icon"
         @click="clearImg()">×</i>
    </div>
    <div v-else>
      <div class="text-center add-video-info"
           v-if="titleInfo">请选择视频</div>
      <div style="float:left"
           class="img-box float-left add-img text-center"
           @click.stop = "selectVideo" ref = "videoInput">
        <label >+</label> 
        <input style="opacity:0;"
               type="file" 
               @change="addVideoEvent" />
      </div>
    </div>
  </div>
</template>

<script>
import * as api from "./../api/api";
import axios from 'axios';
import { IMG_ROOT, OSS_RUL } from './../config'
export default {
    props: {
        video_url: {
            default: "" 
        },
        titleInfo: {
            default: false
        }
    },
    data () {
        return {
            imgRoot: IMG_ROOT,
            loading: false,
            progress: "",
            audioLength: "",
            videoNema: "",
            dataList: "",
            client: ""
        };
    },
    watch:{
        video_url(newVal,oldVal) { 
            console.log(newVal,oldVal);
            if (newVal) { 
                this.dataList = newVal;
            } 
        }
    }, 
    mounted(){
        if(this.video_url){
            this.dataList = this.video_url;
        } 
    },
  methods: {
      
    selectVideo () {
        let els = this.$refs.videoInput.querySelectorAll('input[type=file]')
        els[0].click()
        return false
    },
    myFunction (ele) { 
      let vm = this;
      var hour = parseInt(ele.target.duration / 3600);
      var minute = parseInt((ele.target.duration % 3600) / 60);
      var second = parseInt(ele.target.duration % 60);
      hour = hour < 10 ? "0" + hour : hour;
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      vm.audioLength = `${hour}:${minute}:${second}`;
      vm.$emit("change", vm.dataList, vm.audioLength);
    },
    clearImg () {
      this.$emit("clear");
      this.videoNema = "";
      this.dataList = "";
    },
    // getRight () {
    //   this.client = new OSS.Wrapper({
    //     region: OSS_RUL+'/video',
    //     secure: true,//https
    //     endpoint: OSS_RUL+'/video',
    //     accessKeyId: 'LTAI4FwoNkfFXZmYBwXg6aRv',
    //     /*accessKeyId,accessKeySecret两者到阿里云控制台获得*/
    //     accessKeySecret: 'FROKDq5vfj196CzHd9ArrAQteaBT9f',
    //     bucket: 'hycc' /*装图片的桶名*/
    //   });
    // },
    addVideoEvent (event) {
        var vm = this;
        api.fetchOssSign().then(res=>{
            if(res.data.code==200){
                var video1 = event.target.files[0];
                let ext = event.target.value.toLowerCase().split('.').splice(-1);
                let mathFloor = Math.floor(Math.random() * 90) + 10;
                var storeAs = (new Date()).getTime() + '' + mathFloor + '.' + ext;
                var size = video1.size / 1024;
                // if(size>200){
                //     vm.$message({
                //     showClose: true,
                //     type: 'error',
                //     message: '图片大小不能大于200KB'
                //     });
                //     return false;
                // }
                let formData = new FormData(); 
                formData.append('OSSAccessKeyId', res.data.data.OSSAccessKeyId);
                formData.append('policy', res.data.data.policy);
                formData.append('key', 'video/'+storeAs);
                formData.append('success_action_status', '200');
                formData.append('Signature', res.data.data.Signature); 
                formData.append('file', video1); 
                vm.loading = true;
                axios({
                    url: res.data.data.domain,
                    header:{
                    'Content-Type': 'multipart/form-data'
                    },
                    method: 'post',
                    data: formData
                }).then(ossRes => { 
                    vm.loading = false;
                    if(ossRes.status===200){ 
                        // console.log(ossRes);
                        vm.dataList = res.data.data.domain+'/video/'+storeAs;  
                        vm.$message({
                            message: '上传成功！',
                            type: 'success'
                        });
                    }
                }).catch(function (err) {  
                    vm.loading = false;
                    vm.$message({
                        showClose: true,
                        message: '服务器错误！'
                    })
                })
                event.target.value = ""; 
            }
        })
        // vm.getRight();
        // var file = event.target.files[0];
        // let ext = event.target.value.toLowerCase().split('.').splice(-1);
        // var storeAs = (new Date()).getTime() + '.' + ext;
        // vm.loading = true;
        // // 调用上传方法
        // vm.client.multipartUpload(storeAs, file, {
        //     progress: function* (percentage) {
        //     let fileloadingNum = Math.ceil(percentage * 100) + '%'
        //     vm.progress = fileloadingNum

        //     }
        // }).then(function (res) {
        //     vm.loading = false;
        //     if (res.res.status == 200) {
        //         console.log(res);
        //         // vm.dataList = res.name;
        //         // setTimeout(()=>{
        //         //     vm.$emit('change',vm.dataList,vm.audioLength);
        //         // },1600);
        //         vm.$message({
        //             message: '上传成功！',
        //             type: 'success'
        //         });
        //     }
        // }).catch(function (err) {
        //     console.log(err);
        //     vm.loading = false;
        //     vm.$message({
        //         showClose: true,
        //         message: '服务器错误！'
        //     })
        // })
    }
  }
};
</script>

<style lang="scss" scoped>
.update-img {
  display: inline-block;
  //   margin-left: 10px;
  .add-video-info {
    margin-bottom: 10px;
    color: #fff;
  }
  .img-box {
    position: relative;
    display: inline-block;
    height: 160px;
    width: 160px;
    color: #dedede;
    // margin-right: 20px;
    padding: 20px;
    box-sizing: border-box;
    .img {
      height: 100%;
      width: 100%;
    }
    .clear-icon {
      position: absolute;
      top: 0;
      right: 0;
      padding: 0 6px;
      font-size: 20px;
      border-radius: 50%;
      background: #cd4640;
      color: #fff;
    }
  }
  .add-img {
    line-height: 110px;
    border: 1px dotted #dedede;
    label {
      font-size: 40px;
      display: inline-block;
      text-align: center;
      width: 100%;
      height: 100%;
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 0;
    }
  }
}
</style>
